#!/usr/bin/perl
#save_recovery.cgi

require './diskman-lib.pl';

&ReadParse();

my ($err_msg, $log_ev, $log_msg, $log_pri);

$err_msg="";
$log_ev="";

my $mkfs_lock;
$mkfs_lock = check_lock();
if ($mkfs_lock) {
	$err_msg = $text{"err_mkfslocked"};
	goto ERROR_OUT;
}

my ($volname, $adddisk);
$volname = $in{'volname'};
$adddisk = $in{'adddisk'};
$adddisk =~ /^p(\d+)/;
$dn = $1;
if (!$volname || !$adddisk) {
	$err_msg = $text{"err_cgiparam"};
	goto ERROR_OUT;
}

my (@rdinfo, @dinfo, @free_disks);

@rdinfo = new_get_check_raid_info();
@dinfo = new_get_diskinfo(\@rdinfo);

my $found = 0;
foreach $r (@rdinfo) {
	if ($r->{'name'} eq $volname) {
		$rr = $r;
		$found = 1;
		last;
	}
}

if (!$found) {
	$err_msg = $text{"err_configchanged"};
	goto ERROR_OUT;
}

#if (!new_can_recovery($rr)) {
#	$err_msg = $text{"err_configchanged"};
#	goto ERROR_OUT;
#}

@free_disks = &new_get_free_disks(\@dinfo);
if (!@free_disks) {
	$err_msg = $text{"err_configchanged"};
	goto ERROR_OUT;
}

$found = 0;
my ($fd);
foreach $fd (@free_disks) {
	if ($adddisk eq $fd) {
		$found = 1;
		last;
	}
}

$rr->{'raidlevel'} =~ /RAID-(\d)/;
$raidlevel = "raid".$1;

$cmd_line = $config{'amccpath'}.' /c0/'.$volname." migrate type=$raidlevel disk=".$dn.' 2>/dev/null';

$err_msg = $cmd_line;
#goto ERROR_OUT;

my $out;
$out = `$cmd_line`;
if ($?) {
	$log_ev = $text{'log_ev_recvolume_err'};
	$log_msg= &text('log_msg_recvolume_err', $volname);
	nas_syslog($text{'my_log_minor'}, 'naslog_warning', $log_ev, $log_msg);

	$err_msg = $text{"err_configchanged"};
	goto ERROR_OUT;	
}
$log_ev = $text{'log_ev_recvolume_ok'};
$log_msg= &text('log_msg_recvolume_ok', $volname);
nas_syslog($text{'my_log_minor'}, 'naslog_info', $log_ev, $log_msg);


redirect("mignotice.cgi");

ERROR_OUT:
&error_setup($text{'mig_err_title'});
&error($err_msg);
